﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;


using Visio = Microsoft.Office.Interop.Visio;
using VisioAx = AxMicrosoft.Office.Interop.VisOcx;
using SString = System.String;






namespace WindowsFormsApplication2
{
    //public sealed class AssemblyInfo : ConfigurationElement { }
    public partial class MainForm : Form
    {
        #region GlobalVariables
        string logmsg = "";
        
        string tempstr = "";
        public int itemid = -1;
        public int rackid;

        public Visio.Page currentShapePage;
        public Visio.Page currentRackPage;
        public Visio.Page currentRoomPage;
        public Visio.Page currentBatchPage;

        public Visio.Document currentShapeStencil;
        public Visio.Document currentRackStencil;
        public Visio.Document currentRoomStencil;
        public Visio.Document currentBatchStencil;

        public Visio.Window currentShapeWindow;
        public Visio.Window currentRoomWindow;
        
        Visio.Shape shape;
        Visio.Shape rackshape;
        Visio.Shape horzline;
        Visio.Shape vertline;

        

        int countStencils;
        public string stencilpath;
        public int shapeid;
        public int rackpower;
        public int rackbtu;
        public int rackamp;
        public int itempower;
        public int itembtu;
        public int itemamp;
        public int rackpowerused;
        public int rackbtuused;
        public int rackampused;

        public bool curuseradmin;
        public string curuser;


        List<Rack> myRacks = new List<Rack>();
        List<Item> myItems = new List<Item>();
        public List<int> idlist = new List<int>();
        public List<string> userlist = new List<string>();
        public List<string> racknames = new List<string>();






        int id = 0;
        public int locationX = 0;
        public int locationY = 0;
        public int width = 0;
        public int height = 0;
        public double xoffset = 0.0;
        public double yoffset = 0.0;
        int rackHeight = 0;
        int israck = 0;
        int manId = 0;
        public double rackorgx = 2.0;
        public double rackorgy = 2.0;
        //public string roompath = "C:\\test.vsd";
        //public string roompath = "\\\\10.0.0.20\\Equipment Manager\\Room Diagram\\tif-1st floorv1.vsd";
        //public string roompath = "C:\\tif-1st floorv1.vsd";
        public string roompath = "\\\\10.0.0.20\\Equipment Manager\\Room Diagram\\tif-3rd floorv1.vsd";
        
        
        #endregion
        #region SQLConnection
        SqlConnection mySqlConnection;
        SqlCommand mySqlCommand;
        SqlDataReader myDataReader;

        public void closeConn()//Close SQL Connection
        {
            if (mySqlConnection != null)
            {
                if (mySqlConnection.State == ConnectionState.Open)
                {
                    mySqlConnection.Close();
                }
                mySqlConnection.Dispose();
            }
        }
        public SqlConnection createConn()//Create SQL Connection
        {

            string username = "sqluser";
            string password = "sqluser";
            string server = "10.0.0.20";
            //string wtdatabase = "WISETRACK";
            //string ardatabase = "ARSYSTEMdeveloper";
            string database;
            switch (cDatabase.Text)
            {           
                case "WiseTrack Developer":
                    database = "WISETRACKdeveloper2";
                    break;
                case "WiseTrack LIVE":
                    database = "WISETRACK";
                    break;
                default:
                    database = "WISETRACKdeveloper2";
                    break;
            }

            string myConnString = string.Format("Server={0};Database={1};uid={2};pwd={3};", server, database, username, password);

            if (mySqlConnection == null) { mySqlConnection = new SqlConnection(); };

            if (mySqlConnection.ConnectionString == string.Empty || mySqlConnection.ConnectionString == null)
            {
                try
                {
                    mySqlConnection.ConnectionString = myConnString;
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.Open();

                }
                return mySqlConnection;
            }
            if (mySqlConnection.State != ConnectionState.Open)
            {
                try
                {
                    mySqlConnection.ConnectionString = myConnString;
                    mySqlConnection.Open();
                }
                catch (Exception)
                {
                
                    if (mySqlConnection.State != ConnectionState.Closed)
                    {
                        mySqlConnection.Close();
                    }
                    mySqlConnection.ConnectionString = myConnString;
                    mySqlConnection.Open();
                }
            }
            return mySqlConnection;
        }
        public void closeread()//Close Read Session
        {
            try
            {

                myDataReader.Close();
                mySqlCommand.Dispose();
            }
            catch (Exception ex)
            {
            }
        }
        public void execwrite(string sqlcmd)//Execute Write Command
        {
            try
            {
                mySqlCommand = mySqlConnection.CreateCommand();
                mySqlCommand.CommandText = sqlcmd;
                mySqlCommand.ExecuteNonQuery();
                mySqlCommand.Dispose();
            }
            catch (Exception ex)
            {
            }
        }
        public void execread(string sqlcmd)//Open Read Session, Execute Read Command
        {
            try
            {
                mySqlCommand = mySqlConnection.CreateCommand();
                mySqlCommand.CommandText = sqlcmd;
                myDataReader = mySqlCommand.ExecuteReader();
            }
            catch (Exception ex)
            {
            }
        }
        private void bCONNECT_Click(object sender, EventArgs e)
        {
            LogMessageToFile("Connecting To Database");
            createConn();
            string user = tUserName.Text;
            curuser = user;
            string pass = tPassword.Text;
            string strpass = "";

            string selectuser = string.Format("SELECT USER_NAME,PASSWORD_DB,ADMIN FROM USERS WHERE USER_NAME = '{0}'", user);
            try
            {
                execread(selectuser);


                while (myDataReader.Read())
                {
                    strpass = string.Format("{0}", myDataReader[1]);
                    tempstr = string.Format("{0}", myDataReader[2]);
                    if (Convert.ToInt32(tempstr) == 1)
                    {
                        curuseradmin = true;

                    }
                    else
                    {
                        curuseradmin = false;
                    }
                }
                closeread();

            }
            catch (Exception ex)
            {
            }
            if (!(strpass == pass) || (string.IsNullOrEmpty(pass)))
            {
                closeConn();
                Environment.Exit(-1);
            }
            pConnectProgress.Maximum = 10;
            string racklist = "SELECT NAME FROM LOCATION ORDER BY NAME";
            execread(racklist);
            int i = 0;
            while (myDataReader.Read())
            {
                tConnectStatus.Text = "Connecting...";
                
                pConnectProgress.Increment(1);
                string logmsg = string.Format("{0}", myDataReader[0]);
                //ReadDisplay.AppendText(logmsg);
                //ReadDisplay.AppendText("\r\n");
                RackComboBox.Items.Add(myDataReader[0]);
                i++;
                if(i == pConnectProgress.Maximum){pConnectProgress.Maximum += 1; }

            }
            //ReadDisplay.AppendText(i.ToString());
            closeread();
            tConnectStatus.Text = "Connected";
        }
        private void bCLOSE_Click(object sender, EventArgs e)//Close SQL Database
        {
            closeConn();
            for(int i = pConnectProgress.Value;i >0; i--)
            {
                pConnectProgress.Increment(-1);
            }
            RackComboBox.Items.Clear();
            tConnectStatus.Text = "Disconnected";
        }
        #endregion
        #region Debugging
        public string GetTempPath()
        {
            string path = System.Environment.GetEnvironmentVariable("TEMP");
            if (!path.EndsWith("\\")) path += "\\";
            return path;
        }
        public void LogMessageToFile(string msg)//Write string to text file
        {
            System.IO.StreamWriter sw = System.IO.File.AppendText(
                GetTempPath() + "My Log File.txt");
            try
            {
                string logLine = System.String.Format(
                    /*"{0:G}: {1}.", System.DateTime.Now, */msg);
                sw.WriteLine(logLine);
            }
            finally
            {
                sw.Close();
            }
        }
        //private void ReadButton_Click(object sender, EventArgs e)//Execute Debugging Read String

        //{


        //    string readsql = ReadBox.Text;
        //    execread(readsql);

        //    while (myDataReader.Read())
        //    {
        //        logmsg = string.Format("{0} {1}", myDataReader[0], myDataReader[1]);
        //        //ReadDisplay.AppendText(logmsg);
        //        //ReadDisplay.AppendText("\r\n");

        //    }
        //    closeread();
        //}        
        //private void WriteButton_Click(object sender, EventArgs e)//Execute Debugging Write String
        //{
        //    //UPDATE ITEM SET LOCATIONX = '0';

        //    //if (!myDataReader.IsClosed) { myDataReader.Close(); }
        //    string writesql = WriteBox.Text;
        //    LogMessageToFile(writesql);
        //    //mySqlCommand = mySqlConnection.CreateCommand();
        //    //mySqlCommand.CommandText = writesql;
        //    //mySqlCommand.ExecuteNonQuery();
        //    //mySqlCommand.Dispose();
        //    execwrite(writesql);

        //}
        #endregion
        #region DrawRackDiagram
        //All items are from an example only
        private const string VisioAppID = "visio.application";
        private void bSave_Click(object sender, EventArgs e)
        {
            openFileDialog.DefaultExt = ".vsd";
            openFileDialog.InitialDirectory = "C:\\";
            openFileDialog.ShowDialog();
            string roompath = openFileDialog.FileName;
            Visio.Document document = axRackDiagram1.Document;
            document.SaveAs(roompath);

        }
        private void bDiagram_Click(object sender, EventArgs e)
        {
            
            
            placeshapes();
            foreach (Visio.Window win in axRackDiagram1.Window.Windows)
            {
                if (win.Visible)
                {
                    win.Close();
                }
            }


        }
        public void MoveShape(Visio.Shape newshape, int racky, int rackx, int widthu, int newheight, double delx, double dely)
        {
            double shift = 1.0 / 24.0;
            double posy = rackorgy + .25 + (U2ft(racky -1));
            double posx = rackorgx;
            double widthin = 21.0 / widthu ;
            double center = .49;
            double shapecenter = (double)(rackx - 1.0) / (double)widthu;
            switch (widthu)
            {
                case 1:
                    posx = rackorgx;
                    break;
                case 2:
                    if (shapecenter > center)
                    {
                        posx = rackorgx + .5 - (shift);
                    }
                    else if (shapecenter < center)
                    {
                        posx = rackorgx - .5 + (shift);
                    }
                    break;
                case 4:
                    switch (rackx)
                    {
                        case 1:
                            posx = rackorgx - .66 + (shift);
                            break;
                        case 2:
                            posx = rackorgx - .33 + (shift);
                            break;
                        case 3:
                            posx = rackorgx + .33 - (shift);
                            break;
                        case 4:
                            posx = rackorgx + .66 - (shift);
                            break;
                        default:
                            break;  
                    }
                    break;
                case 8:
                    switch (rackx)
                    {
                        case 1:
                            posx = rackorgx - .8 + (shift);
                            break;
                        case 2:
                            posx = rackorgx - .6 + (shift);
                            break;
                        case 3:
                            posx = rackorgx - .4 + (shift);
                            break;
                        case 4:
                            posx = rackorgx - .2 + (shift);
                            break;
                        case 5:
                            posx = rackorgx + .2 - (shift);
                            break;
                        case 6:
                            posx = rackorgx + .4 - (shift);
                            break;
                        case 7:
                            posx = rackorgx + .6 - (shift);
                            break;
                        case 8:
                            posx = rackorgx + .8 - (shift);
                            break;
                        default:
                            break;  
                    }

                    break;
                default:
                    break;
            }



            newshape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinY)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, posy + dely );
                
            newshape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                   (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinX)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, posx + delx);
        }
        public int ft2U(double num)
        {
            int temp;
            temp = Convert.ToInt32((num * 42.0) / 6.125);
            return temp;
        }
        public double U2ft(int num)
        {
            double temp;
            temp = (num * .146);
            return temp;
        }
        public void placeshapes()
        {
            double drawrackheight = 0.0;
            pProgressRack.Value = 0;
            tempstr = tNumberItems.Text;
            bool validshape = true;
            if (string.IsNullOrEmpty(tempstr)) { pProgressRack.Maximum = 10; }
            else { pProgressRack.Maximum = Convert.ToInt32(tempstr); }
            if(pProgressRack.Maximum == 0){ pProgressRack.Maximum = 10; }

            try
            {
                currentRackPage = axRackDiagram1.Document.Pages[1];
                currentRackPage.Delete(1);
                currentRackPage = axRackDiagram1.Document.Pages[1];

                int placedheight = 1;
                int placedwidth = 1;
                //currentPage.Layout();
                axRackDiagram1.Focus();

                //Insert rack
                string stencilpath = "\\\\10.0.0.20\\Equipment Manager\\visio stencil archive\\Generic\\Generic.vss";

                shapeid = 1;
                currentRackStencil = currentRackPage.Document.Application.Documents.Open(stencilpath);
                rackshape = currentRackPage.Drop(currentRackStencil.Masters[shapeid], rackorgx, rackorgy);
                rackshape.get_Cells("Prop.HoleSpacing.Value").set_Result((short)Visio.VisUnitCodes.visNoCast, 22);
                rackshape.get_Cells("Prop.HoleSpacing.Type").set_Result((short)Visio.VisUnitCodes.visNoCast, 5);

               

                Visio.Shape racknameshape;
                const string styleName = "Text Only";
                racknameshape = currentRackPage.DrawRectangle(.1, 9, 4, 9.5);

                // Set the LineStyle and FillStyle properties of the shape.  The
                // Text Only style is one of the Visio default document styles.
                racknameshape.LineStyle = styleName;
                racknameshape.FillStyle = styleName;




                // Set the shape text with the text passed in.

                racknameshape.Characters.set_CharProps((short)Microsoft.Office.Interop.Visio.
                            VisCellIndices.visCharacterSize,
                        24);

                drawrackheight = U2ft(myRacks[0].rackHeight) * 12.0;


                rackshape.get_Cells("Prop.Height.Value").set_Result((short)Visio.VisUnitCodes.visNoCast, 78);
                CellsIterator.DemoIteratingCellsInShape(rackshape);
                //rackshape.get_RowsCellCount

                //logmsg = rackshape.get_Cells("Prop.Height.Value").get_ResultStr((short)Visio.VisUnitCodes.visNoCast);

                //ReadDisplay.AppendText(logmsg);

                currentRackStencil.Close();
                int progcount = 0;
                foreach (Rack newRack in myRacks)
                {
                    racknameshape.Text = newRack.rackName;
                    if (rackid == newRack.rackID)
                    {
     
                        for (int i = 0; i < newRack.Items.Count;i++)
                        {
                            validshape = true;
                            tempstr = string.Format("{0}", newRack.Items[i].description);
                            stencilpath = newRack.Items[i].visioStencil;
                            shapeid = newRack.Items[i].visioShapeId;
                            if ((shapeid > 0) && (!string.IsNullOrEmpty(stencilpath)))
                            {


                                xoffset = newRack.Items[i].xoff;
                                yoffset = newRack.Items[i].yoff;
                                placedheight = newRack.Items[i].y;
                                if (placedheight == -1) { validshape = false; }
                                placedwidth = newRack.Items[i].x;
                                if (placedwidth == -1) { validshape = false; }
                                width = newRack.Items[i].width;
                                if (width == -1) { validshape = false; }
                                height = newRack.Items[i].height;
                                if (height == -1) { validshape = false; }
                                if (validshape)
                                {
                                    currentRackStencil = currentRackPage.Document.Application.Documents.OpenEx
                                    (stencilpath,
                                    (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);
                                    shape = currentRackPage.Drop(currentRackStencil.Masters[shapeid], 1, 1);
                                    MoveShape(shape, placedheight, placedwidth, width, height, xoffset,yoffset);
                                    currentRackStencil.Close();
                                    //if (width > 1)
                                    //{
                                    //TextOnlyShapeCreation.printlabel
                                    //   (currentRackPage, shape, getmodelnumber(shape), "RIGHTDOWN", newRack.Items[i].height, newRack.Items[i].width, newRack.Items[i].x, newRack.Items[i].y);
                                    //}
                                    //else
                                    //{
                                    try
                                    {
                                        tempstr = newRack.Items[i].manufacturer.ToString() + ", " +
                                            newRack.Items[i].modelNumber.ToString() + ": " +
                                            newRack.Items[i].serialNumber.ToString();
                                    }
                                    catch (Exception ex)
                                    {
                                        tempstr = getmodelnumber(shape);
                                    }
                                    TextOnlyShapeCreation.printlabel
                                   (currentRackPage, tempstr, "RIGHT", newRack.Items[i].height, newRack.Items[i].width, newRack.Items[i].x, newRack.Items[i].y);
                                    //}
                                    pProgressRack.Increment(1);
                                    progcount += 1;

                                    if (pProgressRack.Maximum < (newRack.Items.Count + 3))
                                    {
                                        pProgressRack.Maximum += 1;
                                    }
                                }
                                

                            }
                        }

                    }
                }
                
                drawpowerbox(currentRackPage, rackpower, rackpowerused);
                pProgressRack.Increment(1);
                drawampbox(currentRackPage, rackamp, rackampused);
                pProgressRack.Increment(1);
                drawbtubox(currentRackPage, rackbtu, rackbtuused);
                pProgressRack.Increment(1);
                
                
            }
            catch (Exception ex)
            {
            }
            pProgressRack.Value = pProgressRack.Maximum;

        }
        public void drawpowerbox(Visio.Page targetpage, int powertotal, int powerused)
        {
            double delta;
            if(powertotal == 0) { delta = 0; }
            delta = ((double)powerused/ (double)powertotal);
            if(delta > 1) { delta = 1; }
            Visio.Shape newpowerfillbox;
             newpowerfillbox = targetpage.DrawRectangle(1, 1.5, 1 + 2.0 * delta, 1.75);

            // Set the LineStyle and FillStyle properties of the shape.  The
            // Text Only style is one of the Visio default document styles.
            newpowerfillbox.LineStyle = "None";
            newpowerfillbox.FillStyle = "Normal";

            string color;
            if (delta < .3) { color = "RGB(0,255,0)"; }
            else if(delta < .6) { color = "RGB(255,255,0)"; }
            else { color = "RGB(255,0,0)"; }
                
            newpowerfillbox.get_CellsSRC(
            (short)Visio.VisSectionIndices.visSectionObject,
            (short)Visio.VisRowIndices.visRowFill,
            (short)Visio.VisCellIndices.visFillForegnd)
            .FormulaU = color;

            Visio.Shape newpowertextshape;
            string stylename = "Text Only";
            newpowertextshape = targetpage.DrawRectangle(1,1.5,3,1.75);
            newpowertextshape.LineStyle = "Normal";
            newpowertextshape.FillStyle = stylename;



            // Set the shape text with the text passed in.
            newpowertextshape.Text = "POWER";
            newpowertextshape.Characters.set_CharProps((short)Microsoft.Office.Interop.Visio.
                        VisCellIndices.visCharacterSize,
                    14);


        }

        public void drawampbox(Visio.Page targetpage, int amptotal, int ampused)
        {
            double delta;
            if (amptotal == 0) { delta = 0; }
            delta = ((double)ampused / (double)amptotal);
            if (delta > 1) { delta = 1; }
            Visio.Shape newpowerfillbox;
            newpowerfillbox = targetpage.DrawRectangle(1, 1, 1 + 2.0 * delta, 1.25);

            // Set the LineStyle and FillStyle properties of the shape.  The
            // Text Only style is one of the Visio default document styles.
            newpowerfillbox.LineStyle = "None";
            newpowerfillbox.FillStyle = "Normal";

            string color;
            if (delta < .3) { color = "RGB(0,255,0)"; }
            else if (delta < .6) { color = "RGB(255,255,0)"; }
            else { color = "RGB(255,0,0)"; }

            newpowerfillbox.get_CellsSRC(
            (short)Visio.VisSectionIndices.visSectionObject,
            (short)Visio.VisRowIndices.visRowFill,
            (short)Visio.VisCellIndices.visFillForegnd)
            .FormulaU = color;

            Visio.Shape newpowertextshape;
            string stylename = "Text Only";
            newpowertextshape = targetpage.DrawRectangle(1, 1, 3, 1.25);
            newpowertextshape.LineStyle = "Normal";
            newpowertextshape.FillStyle = stylename;



            // Set the shape text with the text passed in.
            newpowertextshape.Text = "CURRENT";
            newpowertextshape.Characters.set_CharProps((short)Microsoft.Office.Interop.Visio.
                        VisCellIndices.visCharacterSize,
                    14);


        }
        public void drawbtubox(Visio.Page targetpage, int btutotal, int btuused)
        {
            double delta;
            if (btutotal == 0) { delta = 0; }
            delta = ((double)btuused / (double)btutotal);
            if (delta > 1) { delta = 1; }
            Visio.Shape newpowerfillbox;
            newpowerfillbox = targetpage.DrawRectangle(1, .5, 1 + 2.0 * delta, .75);

            // Set the LineStyle and FillStyle properties of the shape.  The
            // Text Only style is one of the Visio default document styles.
            newpowerfillbox.LineStyle = "None";
            newpowerfillbox.FillStyle = "Normal";

            string color;
            if (delta < .3) { color = "RGB(0,255,0)"; }
            else if (delta < .6) { color = "RGB(255,255,0)"; }
            else { color = "RGB(255,0,0)"; }

            newpowerfillbox.get_CellsSRC(
            (short)Visio.VisSectionIndices.visSectionObject,
            (short)Visio.VisRowIndices.visRowFill,
            (short)Visio.VisCellIndices.visFillForegnd)
            .FormulaU = color;

            Visio.Shape newpowertextshape;
            string stylename = "Text Only";
            newpowertextshape = targetpage.DrawRectangle(1, .5, 3, .75);
            newpowertextshape.LineStyle = "Normal";
            newpowertextshape.FillStyle = stylename;



            // Set the shape text with the text passed in.
            newpowertextshape.Text = "BTU";
            newpowertextshape.Characters.set_CharProps((short)Microsoft.Office.Interop.Visio.
                        VisCellIndices.visCharacterSize,
                    14);


        }
        private void bStoreRack_Click(object sender, EventArgs e)
        {
            tempstr = string.Format("UPDATE LOCATION SET RACK_HEIGHT = '{0}' WHERE ID = '{1}'", string.Format("{0}", tRackHeight.Text), rackid);
            execwrite(tempstr);

            tempstr = string.Format("UPDATE LOCATION SET IS_RACK = '{0}' WHERE ID = '{1}'", Convert.ToInt32(ckIsRack.Checked), rackid);
            execwrite(tempstr);

            tempstr = string.Format("UPDATE LOCATION SET POWER = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tPower.Text), rackid);
            execwrite(tempstr);

            tempstr = string.Format("UPDATE LOCATION SET AMP = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tRackAmp.Text), rackid);
            execwrite(tempstr);

            tempstr = string.Format("UPDATE LOCATION SET BTU = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tBTU.Text), rackid);
            execwrite(tempstr);

        }
        
        #endregion
        #region FormControls

        public MainForm()
        {

            
            
            InitializeComponent();
            tabControl.BringToFront();
            
            
            
            double temp;
            temp = (double)Screen.PrimaryScreen.WorkingArea.Width * (1000.0 / 1400.0);
            axRoomDiagram1.Width = (int)temp;
            temp = (double)Screen.PrimaryScreen.WorkingArea.Height * (700.0 / 900.0);
            axRoomDiagram1.Height = (int)temp;

            temp = (double)Screen.PrimaryScreen.WorkingArea.Width * (800.0 / 1400.0);
            axRackDiagram1.Width = (int)temp;
            temp = (double)Screen.PrimaryScreen.WorkingArea.Height * (700.0 / 900.0);
            axRackDiagram1.Height = (int)temp;


            temp = (double)Screen.PrimaryScreen.WorkingArea.Width * (1000.0 / 1400.0);
            axStencilWindow1.Width = (int)temp;
            temp = (double)Screen.PrimaryScreen.WorkingArea.Height * (450.0 / 900.0);
            axStencilWindow1.Height = (int)temp;

            temp = (double)Screen.PrimaryScreen.WorkingArea.Width * (1000.0 / 1400.0);
            axBatchItem.Width = (int)temp;
            temp = (double)Screen.PrimaryScreen.WorkingArea.Height * (450.0 / 900.0);
            axBatchItem.Height = (int)temp;
            WindowState = FormWindowState.Maximized;
            tConnectStatus.Text = "Not Connected";
            cFloor.Items.Add("1st Floor");
            cFloor.Items.Add("3rd Floor");
            cDatabase.Items.Add("WiseTrack Developer");
            cDatabase.Items.Add("WiseTrack LIVE");
            cDatabase.Text = "WiseTrack LIVE";

            
            //string ver = Assembly.GetEntryAssembly().GetName().Version;
            
            //tBuildVer.Text = ver;

        }

        public void rackboxchanged(string selectedrackname)
        {


            bool skip = false;
            string skipstring = "enc";
            Rack newrack = new Rack();
            newrack.Items.Clear();
            Item myitem = new Item();






            pProgressRack.Maximum = 10;

            string logmsg = string.Format("{0}", selectedrackname);
            LogMessageToFile(logmsg);

            string locsql = string.Format("SELECT ID,IS_RACK,RACK_HEIGHT,POWER,BTU,AMP FROM LOCATION WHERE NAME = '{0}'", selectedrackname);
            LogMessageToFile(locsql);
            execread(locsql);

            //try
            //{


                while (myDataReader.Read())
                {
                    
                    rackid = Convert.ToInt32(string.Format("{0}", myDataReader[0]));


                    tempstr = string.Format("{0}", myDataReader[1]);
                    if (tempstr != string.Empty) { israck = Convert.ToInt32(tempstr); }
                    else { israck = 0; }

                    if (tempstr != string.Empty) { rackHeight = Convert.ToInt32(string.Format("{0}", myDataReader[2])); }
                    if (israck == 0) { rackHeight = 0; }

                    tempstr = string.Format("{0}", myDataReader[3]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackpower = Convert.ToInt32(tempstr); }
                    else { rackpower = 0; }

                    tempstr = string.Format("{0}", myDataReader[4]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackbtu = Convert.ToInt32(tempstr); }
                    else { rackbtu = 0; }

                    tempstr = string.Format("{0}", myDataReader[5]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackamp = Convert.ToInt32(tempstr); }
                    else { rackamp = 0; }




                    ckIsRack.Checked = Convert.ToBoolean(israck);
                    tRackHeight.Text = string.Format("{0}", rackHeight);
                    newrack.rackName = selectedrackname;
                    newrack.rackID = rackid;
                    newrack.rackHeight = rackHeight;
                    newrack.power = rackpower;
                    newrack.btu = rackbtu;
                    newrack.amp = rackamp;

                    tPower.Text = rackpower.ToString();
                    tBTU.Text = rackbtu.ToString();
                    tRackAmp.Text = rackamp.ToString();
                    myRacks.Add(newrack);

                    logmsg = string.Format("{0}", rackid);
                    LogMessageToFile(logmsg);


                }
                closeread();






                int i = 0;
                int itemid = 0;
                rackpowerused = 0;
                rackbtuused = 0;
                rackampused = 0;
                
                string rackitemsql = string.Format("SELECT ID, DESCRIPTION,user_field_LOCATIONX,user_field_LOCATIONY,user_field_WIDTH,user_field_HEIGHT,BARCODE,MODEL_NAME,MODEL_NUMBER,SERIAL_NUMBER,MANUFACTURER_ID,VISIO_SHAPE_ID,VISIO_STENCIL,POWER,BTU,AMP,SHAPE_XOFFSET,SHAPE_YOFFSET FROM ITEM WHERE LOCATION_ID = '{0}'", rackid);
                logmsg = string.Format("{0}", rackitemsql);
                LogMessageToFile(logmsg);
                execread(rackitemsql);
                RackItemComboBox.Items.Clear();


                while (myDataReader.Read())
                {
                    
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (tempstr != string.Empty) { id = Convert.ToInt32(tempstr); }

                    string description = string.Format("{0}", myDataReader[1]);

                    
                    tempstr = string.Format("{0}", myDataReader[2]);
                    if (!string.IsNullOrEmpty(tempstr)) { locationX = Convert.ToInt32(tempstr); }
                    else { locationX = -1; }

                    tempstr = string.Format("{0}", myDataReader[3]);
                    if (!string.IsNullOrEmpty(tempstr)) { locationY = Convert.ToInt32(tempstr); }
                    else { locationY = -1; }

                    tempstr = string.Format("{0}", myDataReader[4]);
                    if (!string.IsNullOrEmpty(tempstr)) { width = Convert.ToInt32(tempstr); }
                    else { width = -1; }

                    tempstr = string.Format("{0}", myDataReader[5]);
                    if (!string.IsNullOrEmpty(tempstr)) { height = Convert.ToInt32(tempstr); }
                    else { height = -1; }

                    string barCode = string.Format("{0}", myDataReader[6]);
                    string modelName = string.Format("{0}", myDataReader[7]);
                    string modelNumber = string.Format("{0}", myDataReader[8]);
                    string serialNumber = string.Format("{0}", myDataReader[9]);

                    tempstr = string.Format("{0}", myDataReader[10]);
                    if (!string.IsNullOrEmpty(tempstr)) { manId = Convert.ToInt32(tempstr); }

                    tempstr = string.Format("{0}", myDataReader[11]);
                    if (!string.IsNullOrEmpty(tempstr)) { shapeid = Convert.ToInt32(tempstr); }

                    stencilpath = string.Format("{0}", myDataReader[12]);

                    tempstr = string.Format("{0}", myDataReader[13]);
                    if (!string.IsNullOrEmpty(tempstr)) { itempower = Convert.ToInt32(tempstr); }
                    else { itempower = 0; }

                    tempstr = string.Format("{0}", myDataReader[14]);
                    if (!string.IsNullOrEmpty(tempstr)) { itembtu = Convert.ToInt32(tempstr); }
                    else { itembtu = 0; }

                    tempstr = string.Format("{0}", myDataReader[15]);
                    if (!string.IsNullOrEmpty(tempstr)) { itemamp = Convert.ToInt32(tempstr); }
                    else { itemamp = 0; }

                    tempstr = string.Format("{0}", myDataReader[16]);
                    if (!string.IsNullOrEmpty(tempstr)) { xoffset = Convert.ToDouble(tempstr); }
                    else { xoffset = 0; }

                    tempstr = string.Format("{0}", myDataReader[17]);
                    if (!string.IsNullOrEmpty(tempstr)) { yoffset = Convert.ToDouble(tempstr); }
                    else { yoffset = 0; }


                    


                    myitem = new Item();
                    myitem.itemID = id;
                    //idlist.Add(id)
                    myitem.serialNumber = serialNumber;
                    myitem.modelNumber = modelNumber;
                    myitem.x = locationX;
                    myitem.y = locationY;
                    myitem.height = height;
                    myitem.width = width;
                    myitem.barcode = barCode;
                    myitem.description = description;
                    myitem.modelName = modelName;
                    myitem.manId = manId;
                    myitem.visioShapeId = shapeid;
                    myitem.visioStencil = stencilpath;
                    myitem.power = itempower;
                    myitem.btu = itembtu;
                    myitem.amp = itemamp;
                    myitem.xoff = xoffset;
                    myitem.yoff = yoffset;
                    rackpowerused += itempower;
                    rackbtuused += itembtu;
                    rackampused += itemamp;



                    //newrack.Items.Add(myitem);
                    //newrack.Items.Insert(i, myitem);


                    if (description.Contains(skipstring))
                    {
                        skip = true;
                    }
                    else
                    {
                        skip = false;
                    }

                    if (skip)
                    {
                        newrack.Items.Insert(0, myitem);
                    }
                    else
                    {
                        newrack.Items.Insert(i, myitem);
                    }
                    i++;
                    tempstr = description + ":" + serialNumber;
                    RackItemComboBox.Items.Add(tempstr);
                    
                }
                tPowerUsed.Text = rackpowerused.ToString();
                tBTUUsed.Text = rackbtuused.ToString();
                tAmpUsed.Text = rackampused.ToString();


                Function.setRack(newrack);
                int numitems = itemid;
                closeread();

                string sqlcmd;

                foreach (Rack nextRack in myRacks)
                {
                    foreach (Item myItem in newrack.Items)
                    {
                        sqlcmd = string.Format("SELECT COMPANY FROM COMPANY WHERE ID = '{0}'", myItem.manId);
                        execread(sqlcmd);
                        while (myDataReader.Read())
                        {
                            myItem.manufacturer = string.Format("{0}", myDataReader[0]);
                        }
                        closeread();
                    }
                }
                //Function.SortItemHeight(myItems);
                foreach (Rack nextRack in myRacks)
                {
                    foreach (Item myItem in newrack.Items)
                    {
                        logmsg = string.Format("{0} {1} {2}", myItem.modelNumber, myItem.manufacturer, myItem.description);
                        //ReadDisplay.AppendText(logmsg);
                        //ReadDisplay.AppendText("\r\n");
                    }
                }
                tNumberItems.Text = string.Format("{0}", newrack.Items.Count);
                pProgressRack.Maximum = newrack.Items.Count;
                rackid = newrack.rackID;
            //}
            //catch (Exception ex)
            //{
            //}
        }
        public void RackComboBox_TextChanged(object sender, EventArgs e)//Selected Rack Name has changed
        {
            string rackname = RackComboBox.Text;
            rackboxchanged(rackname);


        }
        private void RackItemComboBox_TextChanged(object sender, EventArgs e)//Selected Item Name has changed
        {
            string selectedDescription;
            string selectedSerialNumber;
            int colonindex;
            tempstr = string.Format("{0}", RackItemComboBox.Text);
            colonindex = tempstr.IndexOf(":");
            selectedDescription = tempstr.Substring(0, colonindex);
            selectedSerialNumber = tempstr.Substring(colonindex + 1);
            //ReadDisplay.AppendText(selectedDescription);
            //ReadDisplay.AppendText("\r\n");
            //ReadDisplay.AppendText(selectedSerialNumber);
            //ReadDisplay.AppendText("\r\n");
            string searchsql = string.Format("SELECT ID FROM ITEM WHERE DESCRIPTION = '{0}' AND SERIAL_NUMBER = '{1}'", selectedDescription, selectedSerialNumber);
            execread(searchsql);
            while (myDataReader.Read())
            {
                tempstr = string.Format("{0}", myDataReader[0]);
            }
            closeread();
            try
            {
                if (!(string.IsNullOrEmpty(tempstr))) { itemid = Convert.ToInt32(tempstr); }
                else { itemid = -1; }
            }
            catch (Exception ex)
            {
            }
            
            itemboxchanged(selectedDescription,selectedSerialNumber, itemid);
        }
        public void itemboxchanged(string desc, string sn, int id)
        {
 
            currentShapePage = axStencilWindow1.Document.Pages[1];
            currentShapePage.Delete(1);
            currentShapePage = axStencilWindow1.Document.Pages[1];
            bool realshapepresent = false;
            bool fakeshape = false;



            if (id <= 0)
            {
                for (int i = 0; i < myRacks.Count; i++)
                {
                    for (int j = 0; j < myRacks[i].Items.Count; j++)
                    {
                        if ((desc == myRacks[i].Items[j].description)
                            & (sn == myRacks[i].Items[j].serialNumber))
                        {
                            id = myRacks[i].Items[j].itemID;
                            //ReadDisplay.AppendText("match");
                            break;
                        }


                    }
                }
            }


            int locid = -1;
            //if (tempstr != string.Empty) { itemid = Convert.ToInt32(tempstr); }

            string idsql = string.Format("SELECT DESCRIPTION,user_field_LOCATIONX,user_field_LOCATIONY,VISIO_SHAPE_ID,VISIO_STENCIL,user_field_WIDTH,user_field_HEIGHT,LOCATION_ID,POWER,BTU,AMP,SHAPE_XOFFSET,SHAPE_YOFFSET FROM ITEM WHERE ID = '{0}'", id);
            itemid = id;
            LogMessageToFile(idsql);
            execread(idsql);
            while (myDataReader.Read())
            {
                string logmsg = string.Format("{0} {1} {2}", myDataReader[0], myDataReader[1], myDataReader[2]);

                tempstr = string.Format("{0}", myDataReader[1]);
                if (!string.IsNullOrEmpty(tempstr)) { locationX = Convert.ToInt32(tempstr); }
                tLX.Text = tempstr;

                tempstr = string.Format("{0}", myDataReader[2]);
                if (!string.IsNullOrEmpty(tempstr)) { locationY = Convert.ToInt32(tempstr); }
                tLY.Text = tempstr;


                tempstr = string.Format("{0}", myDataReader[3]);
                if (!string.IsNullOrEmpty(tempstr)) { shapeid = Convert.ToInt32(tempstr); realshapepresent = true; }
                else { realshapepresent = false; }

                tempstr = string.Format("{0}", myDataReader[4]);
                if (!string.IsNullOrEmpty(tempstr)) 
                { 
                    stencilpath = tempstr; 
                    realshapepresent = true && realshapepresent;
                    tVisioStencilFilePath.Text = stencilpath;
                }
                else { realshapepresent = false; }

                tempstr = string.Format("{0}", myDataReader[5]);
                if (string.IsNullOrEmpty(tempstr)) { fakeshape = false; tItemWidth.Text = ""; }
                else { width = Convert.ToInt32(tempstr); tItemWidth.Text = tempstr; fakeshape = true; }

                tempstr = string.Format("{0}", myDataReader[6]);
                if (string.IsNullOrEmpty(tempstr)) { fakeshape = false; tItemHeight.Text = ""; }
                else { height = Convert.ToInt32(tempstr); tItemHeight.Text = tempstr; fakeshape = true && fakeshape; }

                tempstr = string.Format("{0}", myDataReader[7]);
                if (!string.IsNullOrEmpty(tempstr)) { locid = Convert.ToInt32(tempstr); }
                else { locid = -1; }

                tempstr = string.Format("{0}", myDataReader[8]);
                if (!string.IsNullOrEmpty(tempstr)) { tItemPower.Text = tempstr; }
                else { tItemPower.Text = "0"; }

                tempstr = string.Format("{0}", myDataReader[9]);
                if (!string.IsNullOrEmpty(tempstr)) { tItemBTU.Text = tempstr; }
                else { tItemBTU.Text = "0"; }

                tempstr = string.Format("{0}", myDataReader[10]);
                if (!string.IsNullOrEmpty(tempstr)) { tItemAmp.Text = tempstr; }
                else { tItemAmp.Text = "0"; }

                tempstr = string.Format("{0}", myDataReader[11]);
                if (!string.IsNullOrEmpty(tempstr)) 
                { 
                    tItemXOffset.Text = tempstr;
                    xoffset = Convert.ToDouble(tempstr);
                }
                else { tItemXOffset.Text = "0"; }

                tempstr = string.Format("{0}", myDataReader[12]);
                if (!string.IsNullOrEmpty(tempstr)) 
                { 
                    tItemYOffset.Text = tempstr;
                    yoffset = Convert.ToDouble(tempstr);
                }
                else { tItemYOffset.Text = "0"; }


                if (realshapepresent)//Display Shape if already stored
                {
                    currentShapeStencil = axStencilWindow1.Document.Application.Documents.OpenEx(stencilpath, (short)Visio.VisOpenSaveArgs.visOpenDocked);
                    countStencils = currentShapeStencil.Masters.Count;


                    shape = currentShapePage.Drop(currentShapeStencil.Masters[shapeid], 0, 0);
                    shape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinY)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);

                    shape.get_CellsSRC(
                            (short)Visio.VisSectionIndices.visSectionObject,
                           (short)Visio.VisRowIndices.visRowXFormOut,
                            (short)Visio.VisCellIndices.visXFormPinX)
                            .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);
                    

                    TextOnlyShapeCreation.printlabel
                        (currentShapePage, shape, getmodelnumber(shape), "DOWN");

                    horzline = currentShapePage.DrawLine(0, (4.0 - yoffset), 30, (4.0 - yoffset));
                    vertline = currentShapePage.DrawLine((4.0 - xoffset), 0, (4.0 - xoffset), 50);
                    currentShapePage.Layout();
                    axStencilWindow1.Window.SetViewRect(2, 6, 3, 3);

                }
                
                //else if((realshapepresent == false ) && (fakeshape == true))
                //{
                //    stencilpath = fakestencilpath;
                //    currentStencil = axStencilWindow1.Document.Application.Documents.OpenEx(stencilpath, (short)Visio.VisOpenSaveArgs.visOpenDocked);
                //    countStencils = currentStencil.Masters.Count;
                //}

                LogMessageToFile(logmsg);
                //ReadDisplay.AppendText(logmsg);
                //ReadDisplay.AppendText("\r\n");
            }
            closeread();

            string locsql = string.Format("SELECT NAME FROM LOCATION ORDER BY NAME");
            execread(locsql);
            cItemLocation.Items.Clear();
            while (myDataReader.Read())
            {
                tempstr = string.Format("{0}", myDataReader[0]);
                cItemLocation.Items.Add(tempstr);
                    

            }
            closeread();
            locsql = string.Format("SELECT ID,NAME FROM LOCATION WHERE ID = '{0}'", locid);
            execread(locsql);
            while (myDataReader.Read())
            {
                tempstr = string.Format("{0}", myDataReader[1]);
                cItemLocation.Text = tempstr;

            }
            closeread();


        }
        #endregion
        #region ChooseShape
        
        private void axStencilWindow1_ShapeAdded(object sender, AxMicrosoft.Office.Interop.VisOcx.EVisOcx_ShapeAddedEvent e)
        {
            //currentShapePage = axStencilWindow1.Document.Pages[1];
            for (int i = 1; i < currentShapePage.Shapes.Count; i++)
            {
                tempstr = "\r\n shape added: " + currentShapePage.Shapes[i].Master.IndexInStencil.ToString();
                //ReadDisplay.AppendText(tempstr);

            }
            
            
            //shapeid = currentShapePage.ID;
            //tempstr = shapeid.ToString();
            //ReadDisplay.AppendText(tempstr);
            
        }

        private void bOpenVisioStencilPath_Click(object sender, EventArgs e)
        {
            try
            {
                string path = tVisioStencilFilePath.Text;
                axStencilWindow1.Focus();
                // get the current draw page
                currentShapePage = axStencilWindow1.Document.Pages[1];
                currentShapePage.Delete(1);
                currentShapePage = axStencilWindow1.Document.Pages[1];
                //Visio. axStencilWindow1.Window.Windows.

                foreach (Visio.Window win in axStencilWindow1.Window.Windows)
                {
                    if (win.Visible)
                    {
                        win.Close();
                    }
                }

                /*     For Each win As Visio.Window In Me.VisActiveXControl.Window.Windows
                 If win.Visible Then win.Close() 
             Next*/
                //Visio.ActiveWindow.Windows.ItemFromID(visWinIDShapeSearch).Close();



                // Load the stencil we want
                stencilpath = tVisioStencilFilePath.Text;
                currentShapeStencil = axStencilWindow1.Document.Application.Documents.OpenEx(stencilpath, (short)Visio.VisOpenSaveArgs.visOpenDocked);


                // this gives a count of all the stencils on the status bar
                countStencils = currentShapeStencil.Masters.Count;

                // Drop the first shape of the stencil
                //Visio.Shape shape1 = currentPage.Drop(currentStencil.Masters["Triangle"], 1.50, 1.50);
                shapeid = 1;

                shape = currentShapePage.Drop(currentShapeStencil.Masters[shapeid], 4, 4);


                axStencilWindow1.Window.SetViewRect(2, 6, 3, 3);

                TextOnlyShapeCreation.printlabel
                    (currentShapePage, shape, getmodelnumber(shape), "DOWN");
                horzline = currentShapePage.DrawLine(0, 4, 30, 4);
                vertline = currentShapePage.DrawLine(4, 0, 4, 50);



                
            }
            catch (Exception ex)
            {
            }
            




        }
        private void tVisioStencilFilePath_Click(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = "\\\\10.0.0.20\\Equipment Manager\\visio stencil archive\\";
            openFileDialog.ShowDialog();
            tVisioStencilFilePath.Text = openFileDialog.FileName;
        }
        private string getmodelnumber(Visio.Shape newshape)
        {
            bool propok = false;
            string[] proparray = {/*Cisco*/ "Prop.NetZoomMfgProdNo",
                                     /*Cisco:*/ "Prop.Manufacturer_model_no", 
                                  /*General Dynamics:*/ "Prop.NetZoomMfgDesc",
                                  /*Dell:*/ "Prop.ProductDescription",
                                  

                                    };
            string result = "NULL";
            for (int i = 0; i < proparray.Length; i++)
            {
                //ReadDisplay.AppendText("\r\n");
                //ReadDisplay.AppendText(i.ToString());
                //ReadDisplay.AppendText("\r\n");
                propok = true;
                try
                {
                    result = shape.get_Cells(proparray[i]).get_ResultStr((short)Visio.VisUnitCodes.visNoCast);
                }
                catch (Exception ex)
                {
                    propok = false;
                }
                if (propok)
                {
                    return result;
                }
            }
            return "NO MATCH";


        }
        private void selectshape(int value)
        {
            try
            {
                shapeid = shapeid + value;
                currentShapePage.Delete(1);
                currentShapePage = axStencilWindow1.Document.Pages[1];

                if (shapeid > countStencils) { shapeid = 1; }
                shape = currentShapePage.Drop(currentShapeStencil.Masters[shapeid], 0, 0);
                shape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinY)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);

                shape.get_CellsSRC(
                        (short)Visio.VisSectionIndices.visSectionObject,
                       (short)Visio.VisRowIndices.visRowXFormOut,
                        (short)Visio.VisCellIndices.visXFormPinX)
                        .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);
                

                TextOnlyShapeCreation.printlabel
                    (currentShapePage, shape, getmodelnumber(shape), "DOWN");
                horzline = currentShapePage.DrawLine(0, 4, 30, 4);
                vertline = currentShapePage.DrawLine(4, 0, 4, 50);
                axStencilWindow1.Window.SetViewRect(2, 6, 3, 3);
                currentShapePage.Layout();
                



            }
            catch (Exception ex)
            {
            }
        }
        private void bNextShape_Click(object sender, EventArgs e)
        {
            selectshape(1);

        }
        private void bPrevShape_Click(object sender, EventArgs e)
        {
            selectshape(-1);

        }
        private void bPrevShape10_Click(object sender, EventArgs e)
        {
            selectshape(-10);
        }
        private void bNextShape10_Click(object sender, EventArgs e)
        {
            selectshape(10);
        }
        private void bStoreItem_Click(object sender, EventArgs e)
        {
            //Store shape and stencil, and other parameters.
            int i = 0;
            int locid = -1;
            xoffset = 4.0 - vertline.get_Cells("PinX").get_Result((short)Visio.VisUnitCodes.visNoCast);
            yoffset = 4.0 - horzline.get_Cells("PinY").get_Result((short)Visio.VisUnitCodes.visNoCast);
            tItemXOffset.Text = xoffset.ToString();
            tItemYOffset.Text = yoffset.ToString();
            string locsql = string.Format("SELECT NAME,ID FROM LOCATION ORDER BY NAME");
            execread(locsql);
            while (myDataReader.Read())
            {
                tempstr = string.Format("{0}", myDataReader[0]);
                if (tempstr == cItemLocation.Text)
                {
                    tempstr = string.Format("{0}", myDataReader[1]);
                    if (!string.IsNullOrEmpty(tempstr)) { locid = Convert.ToInt32(tempstr); }
                    else { locid = -1; }
                }
            }
            closeread();

            logmsg = string.Format("{0}", itemid);
            //ReadDisplay.AppendText(logmsg);
            //ReadDisplay.AppendText("\r\n");
            //myRacks[0
           
 
            Rack newrack = new Rack();
            newrack.Items.Clear();
            locsql = string.Format("SELECT ID,IS_RACK,RACK_HEIGHT,POWER,BTU,AMP FROM LOCATION WHERE NAME = '{0}'", cItemLocation.Text);
            LogMessageToFile(locsql);
            execread(locsql);
                
            try
            {


                while (myDataReader.Read())
                {

                    rackid = Convert.ToInt32(string.Format("{0}", myDataReader[0]));


                    tempstr = string.Format("{0}", myDataReader[1]);
                    if (tempstr != string.Empty) { israck = Convert.ToInt32(tempstr); }
                    else { israck = 0; }

                    if (tempstr != string.Empty) { rackHeight = Convert.ToInt32(string.Format("{0}", myDataReader[2])); }
                    if (israck == 0) { rackHeight = 0; }

                    tempstr = string.Format("{0}", myDataReader[3]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackpower = Convert.ToInt32(tempstr); }
                    else { rackpower = 0; }

                    tempstr = string.Format("{0}", myDataReader[4]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackbtu = Convert.ToInt32(tempstr); }
                    else { rackbtu = 0; }

                    tempstr = string.Format("{0}", myDataReader[5]);
                    if (!string.IsNullOrEmpty(tempstr)) { rackamp = Convert.ToInt32(tempstr); }
                    else { rackamp = 0; }




                    ckIsRack.Checked = Convert.ToBoolean(israck);
                    tRackHeight.Text = string.Format("{0}", rackHeight);
                    newrack.rackName = cItemLocation.Text;
                    newrack.rackID = rackid;
                    newrack.rackHeight = rackHeight;
                    newrack.power = rackpower;
                    newrack.btu = rackbtu;
                    newrack.amp = rackamp;

                    tPower.Text = rackpower.ToString();
                    tBTU.Text = rackbtu.ToString();
                    tRackAmp.Text = rackamp.ToString();
                    myRacks.Add(newrack);

                    logmsg = string.Format("{0}", rackid);
                    LogMessageToFile(logmsg);


                }
                closeread();
            }
            catch (Exception ex)
            {
            }
            
            foreach (Rack nextrack in myRacks)
            {
                logmsg = string.Format("{0}", myRacks[i].rackID);

                //ReadDisplay.AppendText(logmsg);
                //ReadDisplay.AppendText("\r\n");
                for (int j = 0; j < myRacks[i].Items.Count; j++)
                {
                    if (itemid == myRacks[i].Items[j].itemID)
                    {
                        if (stencilpath.Contains(":"))
                        {
                            stencilpath = stencilpath.Remove(0, 2);
                            stencilpath = "\\\\10.0.0.20\\Equipment Manager" + stencilpath;
                            //ReadDisplay.AppendText(stencilpath);
                        }
                        logmsg = string.Format("Match");
                        //ReadDisplay.AppendText(logmsg);
                        //ReadDisplay.AppendText("\r\n");
                        try
                        {
                            

                            tempstr = string.Format("UPDATE ITEM SET VISIO_SHAPE_ID = '{0}' WHERE ID = '{1}'", Convert.ToInt32(shapeid), itemid);
                            
                            
                            execwrite(tempstr);
                            tempstr = string.Format("UPDATE ITEM SET VISIO_STENCIL = '{0}' WHERE ID = '{1}'", stencilpath, itemid);
                            
                            execwrite(tempstr);
                            if(!(string.IsNullOrEmpty(tItemWidth.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET user_field_WIDTH = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tItemWidth.Text), itemid);
                                execwrite(tempstr);
                                myRacks[i].Items[j].width = Convert.ToInt32(tItemWidth.Text);
                            }
                            
                            if (!(string.IsNullOrEmpty(tItemHeight.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET user_field_HEIGHT = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tItemHeight.Text), itemid);
                                execwrite(tempstr);
                                myRacks[i].Items[j].height = Convert.ToInt32(tItemHeight.Text);
                            }

                            if (!(string.IsNullOrEmpty(tLX.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET user_field_LOCATIONX = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tLX.Text), itemid);
                                execwrite(tempstr);
                                myRacks[i].Items[j].x = Convert.ToInt32(tLX.Text);
                            }

                            if (!(string.IsNullOrEmpty(tLY.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET user_field_LOCATIONY = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tLY.Text), itemid);
                                execwrite(tempstr);
                                myRacks[i].Items[j].y = Convert.ToInt32(tLY.Text);
                            }

                            tempstr = string.Format("UPDATE ITEM SET LOCATION_ID = '{0}' WHERE ID = '{1}'", locid, itemid);
                            execwrite(tempstr);

                            if (!(string.IsNullOrEmpty(tItemPower.Text)))
                            {

                                tempstr = string.Format("UPDATE ITEM SET POWER = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tItemPower.Text), itemid);
                                execwrite(tempstr);
                            }

                            if (!(string.IsNullOrEmpty(tItemBTU.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET BTU = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tItemBTU.Text), itemid);
                                execwrite(tempstr);
                            }

                            if (!(string.IsNullOrEmpty(tItemAmp.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET AMP = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tItemAmp.Text), itemid);
                                execwrite(tempstr);
                            }
                            if (!(string.IsNullOrEmpty(tItemXOffset.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET SHAPE_XOFFSET = '{0}' WHERE ID = '{1}'", tItemXOffset.Text, itemid);
                                execwrite(tempstr);
                            }
                            if (!(string.IsNullOrEmpty(tItemYOffset.Text)))
                            {
                                tempstr = string.Format("UPDATE ITEM SET SHAPE_YOFFSET = '{0}' WHERE ID = '{1}'", tItemYOffset.Text, itemid);
                                execwrite(tempstr);
                            }
                            myRacks[i].Items[j].visioShapeId = Convert.ToInt32(shapeid);
                            myRacks[i].Items[j].visioStencil = stencilpath;
                            myRacks[i].Items[j].xoff = Convert.ToDouble(tItemXOffset.Text);
                            myRacks[i].Items[j].yoff = Convert.ToDouble(tItemYOffset.Text);
                            
                            
                            
                            
                            
  


                        }
                        catch (Exception ex)
                        {
                        }



                        //ReadDisplay.AppendText(tempstr);
                        //ReadDisplay.AppendText("\r\n");
                        //shapeid;
                        //stencilpath;
                    }

                }
                i++;



            }

        }

        #endregion
        #region DrawRoom
        public string targetrackname;


        private void bOpenRoom_Click(object sender, EventArgs e)
        {
            
            switch(cFloor.Text)
            {
                case "1st Floor": 
                { 
                    roompath = "\\\\10.0.0.20\\Equipment Manager\\Room Diagram\\tif-1st floorv1.vsd";
                    break;
                }
                case "3rd Floor":
                {
                    roompath = "\\\\10.0.0.20\\Equipment Manager\\Room Diagram\\tif-3rd floorv1.vsd";
                    break;
                }
                default:
                {
                    break;
                }
            }

            try
            {
                axRoomDiagram1.Src = roompath;
            }
            catch (Exception ex)
            {
            }
            foreach (Visio.Window win in axRoomDiagram1.Window.Windows)
            {
                if (win.Visible)
                {
                    win.Close();
                }
            }
            currentRoomPage = axRoomDiagram1.Document.Pages[1];
            currentRoomWindow = axRoomDiagram1.Window;
            //GenerateDrawing();
            //ReadDisplay.AppendText(currentRoomPage.Shapes.Count.ToString());




            racknames.Clear();
            racknames = getracknames(currentRoomPage);
            foreach (string rackname in racknames)
            {
                tempstr = "\r\n" + rackname ;
                
                //ReadDisplay.AppendText(tempstr);
            }
            HandleMouseEvents(currentRoomWindow);
        }
        private void GenerateDrawing()
        {
            // Open a document.
            Visio.Document newDocument = setUpDocument();
            if (newDocument != null)
            {
                // Create the Visio drawing.
                // buildVisioDrawing(newDocument);
                currentRoomPage = newDocument.Pages[1];

            }
        }
        private Visio.Document setUpDocument()
        {
            Visio.Document newDocument = null;

            try
            {
                // Open Visio.
                Visio.Application visioApplication = new Visio.Application();

                // Open a new document based on the template.
                newDocument = visioApplication.Documents.OpenEx(roompath,
                    (short)Visio.VisOpenSaveArgs.visOpenCopy);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return newDocument;
        }



        private List<string> getracknames(Visio.Page visPg)
        {
            List<string> racknames = new List<string>();
            // For this example, we will get all shapes on the page

            // that ARE NOT of these:

            //

            //  1. Connectors

            //  2. Foreign objects (like Buttons)

            //  3. Guides
            int i = 0;
            try
            {
                foreach (Visio.Shape shp in visPg.Shapes)
                {
                    short sectionIndex;
                    sectionIndex = (short)Microsoft.Office.Interop.Visio.VisSectionIndices.visSectionObject;
                    if ((shp.OneD == 0) &&
                        (shp.Type != (short)Visio.VisShapeTypes.visTypeForeignObject) &&
                         (shp.Type != (short)Visio.VisShapeTypes.visTypeGuide)
                         && shp.get_Cells("Prop.ShapeType.Value").get_ResultStr((short)Visio.VisUnitCodes.visNoCast).Equals("Cabinet"))
                    {
                        tempstr = "Shape: " + i++.ToString() + "\r\n" + shp.get_Cells("Prop.Elevation.Value").get_ResultStr((short)Visio.VisUnitCodes.visNoCast).ToString();
                        racknames.Add(shp.get_Cells("Prop.Elevation.Value").get_ResultStr((short)Visio.VisUnitCodes.visNoCast).ToString());
                        racknames.Sort();
                        
                        

                    }
                }

            }
            catch (Exception ex)
            {
            }
            return racknames;
        }

        private const string shapesFoundPrompt = 
			"Shapes at the click location:";
		private const string noShapesFoundPrompt = 
			"No shapes at the click location.";

		/// <summary>This window field is the Visio window that is catching the
		/// mouse event.</summary>
		private Microsoft.Office.Interop.Visio.Window clickedWindow;

		/// <summary>This event handler is catching the MouseUp event of the 
		/// window.</summary>
		private Microsoft.Office.Interop.Visio.EWindow_MouseUpEventHandler
			showClickedShapesOnMouseUp_EventHandler;

		/// <summary>This constructor initializes the class by adding a mouseup
		/// event to the specified window.  A mouseup event in the window will
		/// invoke the method that lists the shapes at the click location.
		/// </summary>
		/// <param name="targetWindow">Window that will receive the
		/// mouseup event</param>
		public void HandleMouseEvents(
			Microsoft.Office.Interop.Visio.Window targetWindow) {

			try {

				// Save the window that will receive the event.  This is needed
				// so that the shapes on the window's page can be examined when
				// the mouseup event occurs.
				clickedWindow = targetWindow;

				// Create a new mouseup event for a window.  This will cause
				// the ShowClickedShapes_MouseUpEvent method to be called when
				// the end-user clicks in the window with a mouse button.
				showClickedShapesOnMouseUp_EventHandler = new
					Microsoft.Office.Interop.Visio.EWindow_MouseUpEventHandler(
					showClickedShapes_MouseUpEvent);

				// Add the new mouseup event to the mouseup events for the
				// target window.
				clickedWindow.MouseUp +=
					showClickedShapesOnMouseUp_EventHandler;
                
			}

			catch (Exception error) {
				System.Diagnostics.Debug.WriteLine(error.Message);
				throw;
			}
            
		}
        public Visio.Shape targetrack;
		/// <summary>This method finds the shapes that are at the specified
		/// location.  This is usually used in response to a mouse click event.
		/// </summary>
		/// <param name="clickPage">Page that contains the shapes</param>
		/// <param name="clickXLocation">X coordinate in Visio units
		/// </param>
		/// <param name="clickYLocation">Y coordinate in Visio units
		/// </param>
		/// <param name="tolerance">Distance from the location that a shape
		/// can be to be considered clicked</param>
		/// <returns>Selection object containing the list of shapes at the
		/// specified location (The Selection object is null if an error
		/// occurs.)</returns>
		private static Microsoft.Office.Interop.Visio.Selection 
			getMouseClickShapes(
			Microsoft.Office.Interop.Visio.Page clickPage,
			double clickXLocation,
			double clickYLocation,
			double tolerance) {

			Microsoft.Office.Interop.Visio.Selection clickedShapes = null;
            

			try {

				// Use the SpatialSearch method of the page to get the list
				// of shapes at the location.
                
				clickedShapes = clickPage.get_SpatialSearch(
					clickXLocation, clickYLocation,
					(short)Microsoft.Office.Interop.Visio.
					VisSpatialRelationCodes.visSpatialContainedIn,
					tolerance,
					(short)Microsoft.Office.Interop.Visio.
					VisSpatialRelationFlags.visSpatialFrontToBack);
                    
                
			}

			catch (Exception error) {
				System.Diagnostics.Debug.WriteLine(error.Message);
				throw;
			}

			return clickedShapes;
		}
 
		/// <summary>This method is called when the mouseup event added in
		/// the ShowClickedShapes_On method occurs.  If the left mouse button
		/// was clicked, all shapes at the click location are listed.
		/// </summary>
		/// <param name="button">Button that was clicked to cause this
		/// event to occur</param>
		/// <param name="keyButtonState">State of the shift and control
		/// button  (This parameter is ignored in this method.)</param>
		/// <param name="clickXLocation">X location of the mouse click, in
		/// Visio units</param>
		/// <param name="clickYLocation">Y location of the mouse click, in
		/// Visio units</param>
		/// <param name="cancelProcessing">Flag to set to cancel processing of
		/// the mouse click  (This parameter is ignored in this method.)
		/// </param>
		private void showClickedShapes_MouseUpEvent(
			int button,
			int keyButtonState,
			double clickXLocation,
			double clickYLocation,
			ref bool cancelProcessing) {

            Visio.Shape tempshape;
			double tolerance = 100;

			Microsoft.Office.Interop.Visio.Selection clickedShapes = null;
			int shapeNumber;
			System.Text.StringBuilder message = new System.Text.StringBuilder();

			try {

				// Check if the left mouse button caused this event to occur.
				if (button == (int)Microsoft.Office.Interop.Visio.
					VisKeyButtonFlags.visMouseLeft) {
	              
					// Get the list of shapes at the click location.
					clickedShapes = getMouseClickShapes(
						clickedWindow.PageAsObj, clickXLocation,
						clickYLocation, tolerance);

					// Check if any shapes were found.
					if ((clickedShapes != null) &&
						(clickedShapes.Count > 0)) {


						// Loop through the collection of clicked shapes.
						for (shapeNumber = 1;
							shapeNumber <= clickedShapes.Count;
							shapeNumber ++) 
                        {
                            
							// Show the name of each clicked shape
							
                            tempshape = clickedShapes[1];
                            tempstr = tempshape.get_Cells("Prop.Elevation.Value").get_ResultStr((short)Visio.VisUnitCodes.visNoCast).ToString();
                            foreach (string rackname in racknames)
                            {
                                if (rackname.Equals(tempstr))
                                {
                                    targetrack = tempshape;
                                    //ReadDisplay.AppendText(tempstr);
                                    targetrackname = tempstr;
                                }
                            }
                            
                            
						}
                        tRack.Text = tempstr;

					}
				}
			}

			catch (Exception error) {
				System.Diagnostics.Debug.WriteLine(error.Message);
				throw;
			}
		}
        private void bRoomRackDiagram_Click(object sender, EventArgs e)
        {
            
            tabControl.SelectedTab = tabRack;

            rackboxchanged(tRack.Text.ToString());
            
            placeshapes();
            foreach (Visio.Window win in axRoomDiagram1.Window.Windows)
            {
                if (win.Visible)
                {
                    win.Close();
                }
            }
            foreach (Visio.Window win in axRackDiagram1.Window.Windows)
            {
                if (win.Visible)
                {
                    win.Close();
                }
            }

        }

        private void tRack_TextChanged(object sender, EventArgs e)
        {
            rackboxchanged(tRack.Text);
            int areacircuit = 0;
            int areahvac = 0;
            int locid = -1;

            //Get Rack ID from Text Box.  Don't Really need to do this.
            string areasql = string.Format("SELECT AREA_CB_NAME,ID FROM LOCATION WHERE NAME = '{0}'", tRack.Text);
            execread(areasql);

            string circuitname = "";
            string hvacname = "";
            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}",myDataReader[0]);
                    if (!(string.IsNullOrEmpty(tempstr))) { circuitname = tempstr; }
                    else { cAreaCircuitName.Text = ""; }
                    
                    tempstr = string.Format("{0}", myDataReader[1]);
                    if(!string.IsNullOrEmpty(tempstr)) { locid = Convert.ToInt32(tempstr); }
                    else{ locid = -1; }
                }
                closeread();
            }
            catch (Exception ex)
            {
                
            }


            //Make list of Rack ID's with the same Area Circuit Names
            List<int> loclist = new List<int>();
            areasql = string.Format("SELECT ID FROM LOCATION WHERE AREA_CB_NAME = '{0}'", circuitname);
            execread(areasql);

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if(!(string.IsNullOrEmpty(tempstr))) { loclist.Add(Convert.ToInt32(tempstr)); }
                }
                closeread();
            }

            catch (Exception ex)
            {
            }

            //Add up Area Circuit Numbers.
            for(int i = 0;i < loclist.Count; i++)
            {
                areasql = string.Format("SELECT AMP FROM ITEM WHERE LOCATION_ID = '{0}'", loclist[i]);
                execread(areasql);

                try
                {
                    while (myDataReader.Read())
                    {
                        tempstr = string.Format("{0}", myDataReader[0]);
                        if (!(string.IsNullOrEmpty(tempstr))) { areacircuit += Convert.ToInt32(tempstr); }

                    }
                    closeread();
                }

                catch (Exception ex)
                {
                    tAreaCircuitUsage.Text = "";
                }
            }
            if (string.IsNullOrEmpty(circuitname))
            {
                cAreaCircuitName.Text = "";
                tAreaCircuitUsage.Text = "";
            }
            else
            {
                cAreaCircuitName.Text = circuitname;
                tAreaCircuitUsage.Text = areacircuit.ToString();
            }
            

            
            loclist.Clear();

            areasql = string.Format("SELECT AREA_HVAC_NAME FROM LOCATION WHERE NAME = '{0}'", tRack.Text);
            execread(areasql);

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!(string.IsNullOrEmpty(tempstr))) { hvacname = tempstr; }
                    else { hvacname = ""; }
   
                }
                closeread();
            }
            catch (Exception ex)
            {
                
            }

            //Make list of Rack's with the same Area HVAC System
            areasql = string.Format("SELECT ID FROM LOCATION WHERE AREA_HVAC_NAME = '{0}'", hvacname);
            execread(areasql);

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!(string.IsNullOrEmpty(tempstr))) { loclist.Add(Convert.ToInt32(tempstr)); }
                }
                closeread();
            }

            catch (Exception ex)
            {
            }

            //Add up Area HVAC numbers
            for (int i = 0; i < loclist.Count; i++)
            {
                areasql = string.Format("SELECT BTU FROM ITEM WHERE LOCATION_ID = '{0}'", loclist[i]);
                execread(areasql);

                try
                {
                    while (myDataReader.Read())
                    {
                        tempstr = string.Format("{0}", myDataReader[0]);
                        if (!(string.IsNullOrEmpty(tempstr))) { areahvac += Convert.ToInt32(tempstr); }

                    }
                    closeread();
                }

                catch (Exception ex)
                {
                    tAreaHVACUsage.Text = "";
                }
            }

            if (string.IsNullOrEmpty(hvacname))
            {
                cAreaHVACName.Text = "";
                tAreaHVACUsage.Text = "";
            }
            else
            {
                cAreaHVACName.Text = hvacname;
                tAreaHVACUsage.Text = areahvac.ToString();
            }







                

        }
        public void getareanames()
        {
            string areasql = string.Format("SELECT DISTINCT AREA_CB_NAME FROM LOCATION");
            execread(areasql);
            cAreaCircuitName.Items.Clear();
            cAreaHVACName.Items.Clear();

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!string.IsNullOrEmpty(tempstr)) { cAreaCircuitName.Items.Add(tempstr); }

                }
                closeread();
            }
            catch (Exception ex)
            {
            }
            areasql = string.Format("SELECT DISTINCT AREA_HVAC_NAME FROM LOCATION");
            execread(areasql);

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!string.IsNullOrEmpty(tempstr)) { cAreaHVACName.Items.Add(tempstr); }

                }
                closeread();
            }
            catch (Exception ex)
            {
            }
            foreach (Visio.Window win in axRoomDiagram1.Window.Windows)
            {
                if (win.Visible)
                {
                    win.Close();
                }
            }
        }
        private void tabRoom_Enter(object sender, EventArgs e)
        {
            getareanames();
        }
        private void bStoreArea_Click(object sender, EventArgs e)
        {
            string areasql = string.Format("SELECT ID,NAME FROM LOCATION WHERE NAME = '{0}'", tRack.Text);
            int locid = -1;
            execread(areasql);

            try
            {
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!string.IsNullOrEmpty(tempstr)) { locid = Convert.ToInt32(tempstr); }
                    else { locid = -1; }

                }
                closeread();
            }
            catch (Exception ex)
            {
            }
            try
            {
                tempstr = string.Format("UPDATE LOCATION SET AREA_CB_NAME = '{0}' WHERE ID = '{1}'", cAreaCircuitName.Text, locid);
                execwrite(tempstr);
                tempstr = string.Format("UPDATE LOCATION SET AREA_HVAC_NAME = '{0}' WHERE ID = '{1}'", cAreaHVACName.Text, locid);
                execwrite(tempstr);

            }
            catch (Exception ex)
            {
            }
            getareanames();

        }
        #endregion
        #region Search
        public int selecteditemid;
        
        private void bSEARCH_Click(object sender, EventArgs e)
        {
            cSearchResults.Items.Clear();
            idlist.Clear();
            bool datapresent = false;
            
            string searchsql = "";

            if (!string.IsNullOrEmpty(tSearchSN.Text))
            {
                searchsql = string.Format("SELECT ID,DESCRIPTION,SERIAL_NUMBER FROM ITEM WHERE SERIAL_NUMBER LIKE '%{0}%';",tSearchSN.Text);
            }
            else if (!string.IsNullOrEmpty(tSearchModelNumber.Text))
            {
                searchsql = string.Format("SELECT ID,DESCRIPTION,SERIAL_NUMBER FROM ITEM WHERE DESCRIPTION LIKE '%{0}%';", tSearchModelNumber.Text);
            
            }
            try
            {
                execread(searchsql);
                while (myDataReader.Read())
                {
                    datapresent = true;
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!string.IsNullOrEmpty(tempstr)) { selecteditemid = Convert.ToInt32(tempstr); }

                    tempstr = string.Format("{0}:{1}", myDataReader[1], myDataReader[2]);
   
                    
                    idlist.Add(selecteditemid);
                    cSearchResults.Items.Add(tempstr);
                }
                closeread();
                if (!datapresent)
                {
                    cSearchResults.Items.Clear();
                    cSearchResults.Text = "No Items Found";
                }
                else
                {
                    cSearchResults.Text = tempstr;
                }
            }
            catch (Exception ex)
            {
                cSearchResults.Items.Clear();
                cSearchResults.Text = "No Items Found";
            }


        }
        private void bSearchShow_Click(object sender, EventArgs e)
        {
            try
            {
                int i = cSearchResults.SelectedIndex;
                selecteditemid = idlist[i];
                int locid = 0;
                //ReadDisplay.AppendText(selecteditemid.ToString());
                string searchsql = string.Format("SELECT DESCRIPTION,SERIAL_NUMBER,LOCATION_ID,user_field_LOCATIONX,user_field_LOCATIONY,ID,user_field_WIDTH,user_field_HEIGHT FROM ITEM WHERE ID = '{0}';", selecteditemid);
                execread(searchsql);
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}: {1}", myDataReader[0], myDataReader[1]);

                    //ReadDisplay.AppendText("\r\n" + tempstr);
                    locid = Convert.ToInt32(myDataReader[2]);
                    tSearchLX.Text = myDataReader[3].ToString();
                    tSearchLY.Text = myDataReader[4].ToString();
                    tempstr = string.Format("{0}", myDataReader[5]);
                    if (!string.IsNullOrEmpty(tempstr)) { itemid = Convert.ToInt32(tempstr); }
                    else { itemid = -1; }

                    tempstr = string.Format("{0}", myDataReader[6]);
                    if (!string.IsNullOrEmpty(tempstr)) { width = Convert.ToInt32(tempstr); }
                    else { width = 0; }

                    tempstr = string.Format("{0}", myDataReader[7]);
                    if (!string.IsNullOrEmpty(tempstr)) 
                    { 
                        height = Convert.ToInt32(tempstr);
                        tSearchHeight.Text = tempstr;
                    }
                    else { height = 0; }

                }
                closeread();

                searchsql = string.Format("SELECT ID,NAME FROM LOCATION WHERE ID = '{0}'", locid);
                execread(searchsql);
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    //if (!string.IsNullOrEmpty(tempstr)) { locid = Convert.ToInt32(tempstr); }
                    //else { locid = -1; }

                    tSearchLocation.Text = myDataReader[1].ToString();
                }
                closeread();
                rackboxchanged(tSearchLocation.Text);
                
            }
            catch (Exception ex)
            {
            }

        }
        private void bSearchShowItem_Click(object sender, EventArgs e)
        {
            try
            {
                string selectedDescription;
                string selectedSerialNumber;
                int colonindex;
                selectedSerialNumber = "";
                selectedDescription = "";
                tempstr = string.Format("{0}", cSearchResults.Text);
                colonindex = tempstr.IndexOf(":");
                selectedDescription = tempstr.Substring(0, colonindex);
                selectedSerialNumber = tempstr.Substring(colonindex + 1);
                string searchsql = string.Format("SELECT ID FROM ITEM WHERE DESCRIPTION = '{0}' AND SERIAL_NUMBER = '{1}'", selectedDescription,selectedSerialNumber);
                execread(searchsql);
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                }
                closeread();
                if (!(string.IsNullOrEmpty(tempstr))) { itemid = Convert.ToInt32(tempstr); }
                else { itemid = -1; }
                
                tabControl.SelectedTab = tabItem;
                itemboxchanged(selectedDescription, selectedSerialNumber, itemid);
                RackItemComboBox.Text = cSearchResults.Text;
            }
            catch (Exception ex)
            {
            }

        }
        private void bSearchShowRack_Click(object sender, EventArgs e)
        {
            try
            {
                
                string selectedDescription;
                string selectedSerialNumber;
                int colonindex;
                tempstr = string.Format("{0}", cSearchResults.Text);
                colonindex = tempstr.IndexOf(":");
                selectedDescription = tempstr.Substring(0, colonindex);
                selectedSerialNumber = tempstr.Substring(colonindex + 1);
                string searchsql = string.Format("SELECT ID,user_field_HEIGHT FROM ITEM WHERE DESCRIPTION = '{0}' AND SERIAL_NUMBER = '{1}'", selectedDescription, selectedSerialNumber);
                execread(searchsql);
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    
                }
                closeread();
                if (!(string.IsNullOrEmpty(tempstr))) { itemid = Convert.ToInt32(tempstr); }
                else { itemid = -1; }
                rackboxchanged(tSearchLocation.Text);
                tabControl.SelectedTab = tabRack;
                placeshapes();
                foreach (Visio.Window win in axRackDiagram1.Window.Windows)
                {
                    if (win.Visible)
                    {
                        win.Close();
                    }
                }
                drawboundbox(Convert.ToInt32(tSearchLY.Text), Convert.ToInt32(tSearchHeight.Text));
            }
            catch (Exception ex)
            {
            }

        }
        public void drawboundbox(int locy, int itemheight)
        {
            Visio.Shape boundbox;
            const string styleName = "Text Only";
            double ystart = U2ft(locy + 1) + 1.9;
            double ystop = U2ft(locy + itemheight + 1) + 2;
            
            boundbox = currentRackPage.DrawRectangle(.9, ystart, 3.1,ystop);

            // Set the LineStyle and FillStyle properties of the shape.  The
            // Text Only style is one of the Visio default document styles.
            boundbox.LineStyle = "Normal";
            boundbox.FillStyle = "None";
            
            boundbox.get_Cells("LineColor").set_Result((short)Visio.VisUnitCodes.visNoCast, 2);
            
        }
        private void tabSearch_Enter(object sender, EventArgs e)
        {
            tSearchModelNumber.Clear();
            tSearchSN.Clear();
        }
        #endregion
        #region Batch

        private void tabControl_Enter(object sender, EventArgs e)
        {
            tBatchModelNumber.Clear();
        }
        private void bBatchSearch_Click(object sender, EventArgs e)
        {
            cBatchResults.Items.Clear();
            
            idlist.Clear();
            bool datapresent = false;

            string searchsql = "";

            if (!string.IsNullOrEmpty(tBatchModelNumber.Text))
            {
                searchsql = string.Format("SELECT ID,DESCRIPTION,SERIAL_NUMBER FROM ITEM WHERE DESCRIPTION LIKE '%{0}%';", tBatchModelNumber.Text);

            }
            try
            {
                execread(searchsql);
                while (myDataReader.Read())
                {
                    datapresent = true;
                    tempstr = string.Format("{0}", myDataReader[0]);
                    if (!string.IsNullOrEmpty(tempstr)) { selecteditemid = Convert.ToInt32(tempstr); }

                    tempstr = string.Format("{0}:{1}", myDataReader[1], myDataReader[2]);


                    idlist.Add(selecteditemid);
                    cBatchResults.Items.Add(tempstr);
                }
                closeread();
                if (!datapresent)
                {
                    cBatchResults.Items.Clear();
                    cBatchResults.Text = "No Items Found";
                }
                else
                {
                    cBatchResults.Text = tempstr;
                }
            }
            catch (Exception ex)
            {
                cBatchResults.Items.Clear();
                cBatchResults.Text = "No Items Found";
            }

            
        }
        private void tBatchFile_Click(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = "\\\\10.0.0.20\\Equipment Manager\\visio stencil archive\\";
            openFileDialog.ShowDialog();
            tBatchFile.Text = openFileDialog.FileName;
        }

        private void bBatchOpen_Click(object sender, EventArgs e)
        {
            try
            {
                string path = tVisioStencilFilePath.Text;

                axBatchItem.Focus();
                // get the current draw page
                currentBatchPage = axBatchItem.Document.Pages[1];
                currentBatchPage.Delete(1);
                currentBatchPage = axBatchItem.Document.Pages[1];
                //Visio. axStencilWindow1.Window.Windows.

                foreach (Visio.Window win in axBatchItem.Window.Windows)
                {
                    if (win.Visible)
                    {
                        win.Close();
                    }
                }


                //Visio.ActiveWindow.Windows.ItemFromID(visWinIDShapeSearch).Close();



                // Load the stencil we want
                stencilpath = tBatchFile.Text;
                currentBatchStencil = axBatchItem.Document.Application.Documents.OpenEx(stencilpath, (short)Visio.VisOpenSaveArgs.visOpenDocked);


                // this gives a count of all the stencils on the status bar
                countStencils = currentBatchStencil.Masters.Count;

                // Drop the first shape of the stencil
                //Visio.Shape shape1 = currentPage.Drop(currentStencil.Masters["Triangle"], 1.50, 1.50);
                shapeid = 1;

                shape = currentBatchPage.Drop(currentBatchStencil.Masters[shapeid], 0, 0);
                shape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinY)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);

                shape.get_CellsSRC(
                        (short)Visio.VisSectionIndices.visSectionObject,
                       (short)Visio.VisRowIndices.visRowXFormOut,
                        (short)Visio.VisCellIndices.visXFormPinX)
                        .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);
                

                TextOnlyShapeCreation.printlabel
                    (currentBatchPage, shape, getmodelnumber(shape), "DOWN");




                
                horzline = currentBatchPage.DrawLine(0, 4, 30, 4);
                vertline = currentBatchPage.DrawLine(4, 0, 4, 50);
                axBatchItem.Window.SetViewRect(2, 6, 3, 3);
                currentBatchPage.Layout();
                
            }
            catch (Exception ex)
            {
            }

        }

        private void batchselectshape(int value)
        {
            try
            {
                shapeid = shapeid + value;
                currentBatchPage.Delete(1);
                currentBatchPage = axBatchItem.Document.Pages[1];

                if (shapeid > countStencils) { shapeid = 1; }
                shape = currentBatchPage.Drop(currentBatchStencil.Masters[shapeid], 0, 0);
                shape.get_CellsSRC(
                    (short)Visio.VisSectionIndices.visSectionObject,
                    (short)Visio.VisRowIndices.visRowXFormOut,
                    (short)Visio.VisCellIndices.visXFormPinY)
                    .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);

                shape.get_CellsSRC(
                        (short)Visio.VisSectionIndices.visSectionObject,
                       (short)Visio.VisRowIndices.visRowXFormOut,
                        (short)Visio.VisCellIndices.visXFormPinX)
                        .set_Result((short)Visio.VisUnitCodes.visNoCast, 4);


                TextOnlyShapeCreation.printlabel
                    (currentBatchPage, shape, getmodelnumber(shape), "DOWN");
                horzline = currentBatchPage.DrawLine(0, 4, 30, 4);
                vertline = currentBatchPage.DrawLine(4, 0, 4, 50);
                axBatchItem.Window.SetViewRect(2, 6, 3, 3);
                currentBatchPage.Layout();

            }
            catch (Exception Ex)
            {
            }
        }
        private void bBatchNext_Click(object sender, EventArgs e)
        {
            batchselectshape(1);

        }
        private void bBatchNext10_Click(object sender, EventArgs e)
        {
            batchselectshape(10);
        }
        private void bBatchPrevious_Click(object sender, EventArgs e)
        {
            batchselectshape(-1);
        }

        private void bBatchPrevious10_Click(object sender, EventArgs e)
        {
            batchselectshape(-10);
        }


        private void bBatchStore_Click(object sender, EventArgs e)
        {

            
            xoffset = 4.0 - vertline.get_Cells("PinX").get_Result((short)Visio.VisUnitCodes.visNoCast);
            yoffset = 4.0 - horzline.get_Cells("PinY").get_Result((short)Visio.VisUnitCodes.visNoCast);
            tBatchXOffset.Text = xoffset.ToString();
            tBatchYOffset.Text = yoffset.ToString();

            int i = 0;
            try
            {

                for (i = 0; i < idlist.Count; i++)
                {

                    tempstr = string.Format("UPDATE ITEM SET VISIO_STENCIL = '{0}' WHERE ID = '{1}'", stencilpath, idlist[i]);
                    if (!string.IsNullOrEmpty(stencilpath))
                    {
                        execwrite(tempstr);
                        tempstr = string.Format("UPDATE ITEM SET VISIO_SHAPE_ID = '{0}' WHERE ID = '{1}'", Convert.ToInt32(shapeid), idlist[i]);
                        execwrite(tempstr);
                    }

                    if (!(string.IsNullOrEmpty(tBatchPower.Text)))
                    {

                        tempstr = string.Format("UPDATE ITEM SET POWER = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tBatchPower.Text), idlist[i]);
                        execwrite(tempstr);
                    }

                    if (!(string.IsNullOrEmpty(tBatchBTU.Text)))
                    {
                        tempstr = string.Format("UPDATE ITEM SET BTU = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tBatchBTU.Text), idlist[i]);
                        execwrite(tempstr);
                    }

                    if (!(string.IsNullOrEmpty(tBatchAmp.Text)))
                    {
                        tempstr = string.Format("UPDATE ITEM SET AMP = '{0}' WHERE ID = '{1}'", Convert.ToInt32(tBatchAmp.Text), idlist[i]);
                        execwrite(tempstr);
                    }

                    if (!(string.IsNullOrEmpty(tBatchXOffset.Text)))
                    {
                        tempstr = string.Format("UPDATE ITEM SET SHAPE_XOFFSET = '{0}' WHERE ID = '{1}'", tBatchXOffset.Text, idlist[i]);
                        execwrite(tempstr);
                    }
                    if (!(string.IsNullOrEmpty(tBatchYOffset.Text)))
                    {
                        tempstr = string.Format("UPDATE ITEM SET SHAPE_YOFFSET = '{0}' WHERE ID = '{1}'", tBatchYOffset.Text, idlist[i]);
                        execwrite(tempstr);
                    }
                }
            }
            catch (Exception ex)
            {
            }


        }
        #endregion
        #region Admin
        bool userfill = false;
        private void tabAdmin_Enter(object sender, EventArgs e)
        {
            string tempstr2;
            userlist.Clear();
            cUsers.Items.Clear();
            
            string listusers = "SELECT LAST_NAME,FIRST_NAME,USER_NAME FROM USERS ORDER BY LAST_NAME";
            try
            {
                execread(listusers);
                while (myDataReader.Read())
                {
                    userfill = false;
                    tempstr = string.Format("{0},{1}", myDataReader[0], myDataReader[1]);
                    cUsers.Items.Add(tempstr);
                    tempstr2 = string.Format("{0}", myDataReader[2]);
                    userlist.Add(tempstr2);
                }
                cUsers.Text = tempstr;
                userfill = true;
                closeread();
            }
            catch (Exception Ex)
            {
            }

        }
        private void userchanged(string testuser)
        {
            string readusers = string.Format("SELECT USER_NAME,PASSWORD_DB,ADMIN FROM USERS WHERE USER_NAME = '{0}'",testuser);
            try
            {
                execread(readusers);
                while (myDataReader.Read())
                {
                    tempstr = string.Format("{0}", myDataReader[0]);
                    tAdminUserName.Text = tempstr;
                    tempstr = string.Format("{0}", myDataReader[1]);
                    tAdminPassword.Text = tempstr;
                    tempstr = string.Format("{0}", myDataReader[2]);
                    if (!string.IsNullOrEmpty(tempstr))
                    {
                        cbAdmin.Checked = Convert.ToBoolean(Convert.ToInt32(tempstr));
                    }
                    else
                    {
                        cbAdmin.Checked = false;
                    }
                }
                closeread();
            }
            catch (Exception ex)
            {
            }

        }
        int seluserid;
        private void cUsers_TextChanged(object sender, EventArgs e)
        {
            seluserid = cUsers.SelectedIndex;
            if (curuseradmin & userfill)
            {
                userchanged(userlist[seluserid]);
            }

        }

        private void bAdminSave_Click(object sender, EventArgs e)
        {
            string tempstr2;
            try
            {
                bool curuservalidated = false;
                string seluser = userlist[seluserid];
                if (curuser == seluser)
                {
                    curuservalidated = true;
                }
                if (curuservalidated || curuseradmin)
                {
                    //Update ID/Password
                    tempstr = string.Format("{0}", tAdminPassword.Text);
                    if (!string.IsNullOrEmpty(tempstr))
                    {
                        tempstr2 = string.Format("UPDATE USERS SET PASSWORD_DB = '{0}' WHERE USER_NAME = '{1}'", tempstr, seluser);
                        execwrite(tempstr2);
                    }

                    
                }
                if (curuseradmin)
                {
                    //Update Admin Status
                    tempstr = string.Format("UPDATE USERS SET ADMIN = {0} WHERE USER_NAME = '{1}'", Convert.ToInt32(cbAdmin.Checked), seluser);
                    execwrite(tempstr);

                }
            }
            catch (Exception ex)
            {
            }


        }
        #endregion










    }

       
}

